<?php
//var_dump($_POST['field'][2]['tbl_classtime']);exit;
ini_set('memory_limit', '50M');
ini_set('set_time_limit', 1800);
set_include_path($_SERVER['DOCUMENT_ROOT']);
$error = "网页状态已经过期，请刷新页面";
include 'admin/includes/functions/admin-functions.php';

$classtime_arr = [];
if (checkToken('admin', $_POST['formToken'])) {
    $isInsert = false;
    $additional = array();
    $tables = $DBobject->ShowTables();
    if ($tables) {
        $returnIDs = array();
        $stored = array();
        $fields = $_POST['field'];

        foreach ($fields as $order => $set) {
            foreach ($set as $tbl => $group) {
                if (in_array($tbl, $tables)) {
                    if ($tbl=='tbl_classtime') {
                        $classtime_arr = $group;
                    } else {
                        foreach ($group as $index => $vals) {
                            $id = $vals['id'];
                            if (!is_array($id)) {
                                $id = array($id);
                            }
                            $id_check = array();
                            $_update_vals = array();
                            $_insert_vals = array();
                            $_insert_fields = array();
                            $_params = array();
                            $additionalAction = 'Edit';
                            $additionalIDs = array();
                            if (is_array($vals)) {
                                foreach ($vals as $key => $val) {
                                    if ($key == 'id') {
                                        continue;
                                    }
                                    if (in_array($key, $id)) {
                                        $id_check[] = "{$key} = :{$key}";
                                        $additionalIDs[] = $val;
                                    } else {
                                        if (empty($val) && array_key_exists($key, $_POST['default'])) {
                                            $val = $stored["{$_POST['default']["{$key}"]}"];
                                        }
                                        $_update_vals[] = "{$key} = :{$key} ";
                                        $_insert_vals[] = ":{$key} ";
                                        $_insert_fields[] = "{$key}";
                                        $_params["{$key}"] = $val;
                                        if (preg_match('/deleted/', $key)) {
                                            $additionalAction = 'Delete';
                                        }
                                    }
                                }
                            }
                            $nvalues = 0;
                            foreach ($id as $i) {
                                if ($vals["{$i}"] != '') {
                                    ++$nvalues;
                                }
                            }
                            $insert_table = '';
                            if (count($id) > $nvalues) {
                                $sql = "INSERT INTO {$tbl} (".implode(',', $_insert_fields).') VALUES ('.implode(',', $_insert_vals).')';
                                $insert_table = $tbl;
                            } else {
                                foreach ($id as $i) {
                                    $_params["{$i}"] = $vals["{$i}"];
                                    if ($_POST['primary_id'] == $i) {
                                        $primaryID = $vals["{$i}"];
                                        $primaryTable = $tbl;
                                        $primaryAction = $additionalAction;
                                    }
                                }
                                $sql = "UPDATE {$tbl} SET ".implode(',', $_update_vals).' WHERE '.implode(' AND ', $id_check);
                                $update_table = $tbl;

                                if ($primaryTable != $tbl) {
                                    $additional[] = "$additionalAction|$tbl|".implode(':', $additionalIDs);
                                }
                            }
                            $result = $DBobject->executeSQL($sql, $_params);

                            if (empty($stored)) {
                                $stored = $_params;
                            } else {
                                if (!empty($_params)) {
                                    $stored = array_merge($stored, $_params);
                                }
                            }

                            if ($insert_table != '') {
                                $o = $DBobject->wrappedSqlIdentity();
                                foreach ($id as $i) {
                                    $key = "field[{$order}][{$tbl}][{$index}][{$i}]";
                                    $returnIDs[$key] = $o;

                                    $stored["{$i}"] = $o;
                                    if ($_POST['primary_id'] == $i) {
                                        $isInsert = true;
                                        $primaryID = $o;
                                        $primaryTable = $tbl;
                                        $primaryAction = 'Add';
                                    } else {
                                        $additional[] = "Add|$tbl|$o";
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
} else {
    echo json_encode([
        'notice' => 'error',
        'error' => $error
    ]);
    die();
}

global $EDITED;

if(!empty($classtime_arr)){
    //删除原始
    //var_dump($classtime_arr);exit;
    $_insert_fields = [];
    $_insert_tmp = [];
    $_insert_vals = [];
    $_insert_str = '';
    $_params = [];
    $class_weekday = '';
    $sql = "DELETE FROM tbl_classtime WHERE classtime_class_id = {$primaryID}";
    $DBobject->executeSQL($sql);
    $i = 0;
    foreach ($classtime_arr as $key => $val) {
        $_insert_fields[] = $key;
        if ($key=="classtime_class_id") {
            continue;
        }
        if ($key=="classtime_weekday") {
            $class_weekday = implode(',', $val);
        }
        foreach ($val as $k => $v) {
            $_insert_tmp[$k][$key] = $v;
            $i++;
        }
    }
    foreach ($_insert_tmp as $k => $v) {
        $_temp[$k][] = ':classtime_class_id'.$k;
        $_params["classtime_class_id{$k}"] = $primaryID;
        foreach ($v as $key => $value) {
            $_temp[$k][] = ':'.$key.$k;
            $_params["{$key}{$k}"] = $value;
        }
        $_insert_vals[] = '('.implode(',', $_temp[$k]).')';
    }
    $_insert_str = implode(',', $_insert_vals);
    $sql = "INSERT INTO tbl_classtime (" . implode(',', $_insert_fields) . ") VALUES ".$_insert_str;
    //var_dump($sql);exit;
    $result = $DBobject->executeSQL($sql, $_params);

    //更新class表字段，设置class_weekday
    $sql = "UPDATE tbl_class SET class_weekday=:class_weekday WHERE class_id= {$primaryID}";
    $_params = [':class_weekday'=>$class_weekday];
    $DBobject->executeSQL($sql, $_params);

}

if ($isInsert) {

    $DBobject->executeSQL($sql, $_params);

    saveInLog($primaryAction, $primaryTable, $primaryID, implode(',', $additional));
    echo json_encode(array(
            'notice' => $EDITED,
            'IDs' => $returnIDs,
            'primaryID' => $primaryID,
    ));
} else {
    saveInLog($primaryAction, $primaryTable, $primaryID, implode(',', $additional));
    echo json_encode(array(
            'notice' => $EDITED,
            'IDs' => $returnIDs,
    ));
}
die();
